package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import model.ServerRequest;

public class RequestHandler implements Runnable {

	private final ServerRequest request;
	private final String host;
	private final int port;
	
	public RequestHandler(String host, int port, ServerRequest sr) {
		request = sr;
		this.host = host;
		this.port = port;
	}

	@Override
	public void run() {
		try {
			// Establishes connection
			Socket socket = new Socket(host, port);
			
			// grabs the inout streams
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			
			// Send request			
			out.writeObject(request.getRequest());
			out.flush();
			
			// get the server response
			request.processReply((String)in.readObject());
		}catch (ConnectException conex){
			System.out.printf("RequestHandler> Can't connect to %s:%d%n", host, port);
		}catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("\r\nRequestHandler> the socket was disconnected. Probably server is gone\n\rUser>");
		} catch (ClassNotFoundException e) {
			System.out.println("RequestHandler> Can't cast to string");
			e.printStackTrace();
		}
	}

}
